package dk.cs.wolverine.client;

import java.util.ArrayList;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import dk.cs.wolverine.shared.Section;

/**
 * This is the implementation of the setup part where you can add new sections
 * and questions.
 * 
 * @author Kalle
 * 
 */
public class Setup implements EntryPoint {

	private QuestionnaireServiceAsync server = GWT.create(QuestionnaireService.class);
	private ArrayList<Section> sections;

	@Override
	public void onModuleLoad() {
		updateSections();
	}

	private Widget showCreateSection() {
		HorizontalPanel hp = new HorizontalPanel();
		final TextBox newSection = new TextBox();
		newSection.setTitle("Enter the new section's name");
		hp.add(newSection);
		Button btn = new Button("Add", new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				String text = newSection.getText();
				if (!"".equals(text)) {
					boolean sectionExists = false;
					for (Section sec : sections) {
						if (sec.getName().equalsIgnoreCase(text))
							sectionExists = true;
					}
					if (!sectionExists) {
						// Only add the new section if we do not have a section
						// with that name already
						Section section = new Section(text);
						server.addSection(section, new AsyncCallback<Void>() {
							@Override
							public void onFailure(Throwable caught) {
								Window.alert("RPC error occured");
							}

							@Override
							public void onSuccess(Void result) {
								newSection.setText("");
								updateSections();
							}
						});
						return;
					}
					Window.alert("A section with that name already exists, please choose another name");
				}
				Window.alert("You must set a name for the new section");
			}
		});
		hp.add(btn);
		return hp;
	}

	private Widget showCreateQuestion() {

		HorizontalPanel hp = new HorizontalPanel();
		final ListBox secs = new ListBox(false);
		for (Section sec : sections) {
			secs.addItem(sec.getName());
		}
		secs.setVisibleItemCount(1);
		hp.add(secs);
		final TextBox newQuestion = new TextBox();
		newQuestion.setTitle("Enter the new question here");
		hp.add(newQuestion);
		RadioButton textQuestion = new RadioButton("questionType", "Text question");
		final RadioButton selectQuestion = new RadioButton("questionType", "Selectbox question");
		hp.add(textQuestion);
		hp.add(selectQuestion);
		final TextBox posibleAnswers = new TextBox();
		posibleAnswers.setTitle("Enter the posible choices in a semicolon seperated fashion i.e. choice1;choice2; choice3");
		posibleAnswers.setVisible(false);
		posibleAnswers.setText("example1;example2");
		hp.add(posibleAnswers);
		textQuestion.setValue(true);
		textQuestion.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				if (event.getValue().booleanValue()) {
					// The text question was chosen
					posibleAnswers.setVisible(false);
				}
			}
		});

		selectQuestion.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				if (event.getValue().booleanValue()) {
					// The select question was chosen
					posibleAnswers.setVisible(true);
				}
			}
		});


		Button btn2 = new Button("Add", new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				String choosenSection = secs.getItemText(secs
						.getSelectedIndex());
				Section section = null;
				for (Section sec : sections) {
					if (sec.getName().equals(choosenSection)) {
						section = sec;
					}
				}

				if (section != null) {
					String text = newQuestion.getText();
					if (!"".equals(text)) {
						boolean questionExists = false;
						//System.out.println("NUMBER OF QUESTIONS: " + section.getQuestions().size());
						/*for (Question q : section.getQuestions()) {
							if (q.getQuestion().equalsIgnoreCase(text)) {
								questionExists = true;
							}
						}*/
						if (!questionExists) {
							//Only add if a question with the same text does not exist
							if (selectQuestion.getValue()) {
								//The select question was chosen so we split the possible answers
								String[] answers = posibleAnswers.getText()
								.split(";");
								ArrayList<String> list = new ArrayList<String>();
								for (int i = 0; i < answers.length; i++) {
									String answer = answers[i].trim();
									list.add(answer);
								}
								System.out.println("SECTION " + section.getName() + " text " + text + " list " + list);
								server.addSelectionQuestion(section, text,
										list, new AsyncCallback<Void>() {
									@Override
									public void onFailure(
											Throwable caught) {
										Window.alert("RPC error occured");
									}

									@Override
									public void onSuccess(Void result) {
										//Window.alert("SELECT");
									}
								});
							} else {
								//The plain text question was chosen
								server.addTextQuestion(section, text,
										new AsyncCallback<Void>() {

									@Override
									public void onFailure(
											Throwable caught) {
										Window.alert("RPC error occured");
									}

									@Override
									public void onSuccess(Void result) {
										//Window.alert("TEXT");
									}
								});
							}
						} else {
							Window.alert("A question with that text already exists");
						}
					} else {
						Window.alert("You must enter a question");
					}
				} else {
					Window.alert("The choosen section could not be found in the list of sections");
				}
			}
		});
		hp.add(btn2);
		return hp;
	}

	private void updateSections() {
		//Get fresh list of sections from server
		server.getSections(new AsyncCallback<ArrayList<Section>>() {
			@Override
			public void onSuccess(ArrayList<Section> sectionList) {
				sections = sectionList;
				VerticalPanel vp = new VerticalPanel();
				vp.add(new HTML("<h1>Questionnaire setup.</h1>"));
				vp.add(new HTML("<hr />"));
				vp.add(new HTML("<h2>Add section</h2>"));
				vp.add(showCreateSection());
				vp.add(new HTML("<hr />"));
				vp.add(new HTML("<h2>Add Question</h2>"));
				vp.add(showCreateQuestion());
				RootPanel.get("content").clear();
				RootPanel.get("content").add(vp);
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("ERROR GETTING SECTIONS\n" + caught.getMessage());
			}
		});
	}
}